import { onMounted, onUnmounted, reactive } from 'vue'

export function useControls() {
  const controls = reactive({
    left: false,
    right: false,
    up: false,
    down: false,
    attack1: false,
    attack2: false,
    special: false
  })
  
  const keyMap = {
    'ArrowLeft': 'left',
    'ArrowRight': 'right',
    'ArrowUp': 'up',
    'ArrowDown': 'down',
    'KeyZ': 'attack1',
    'KeyX': 'attack2',
    'KeyC': 'special',
    'KeyA': 'left',
    'KeyD': 'right',
    'KeyW': 'up',
    'KeyS': 'down',
    'KeyJ': 'attack1',
    'KeyK': 'attack2',
    'KeyL': 'special'
  }
  
  const onKeyDown = (e) => {
    const control = keyMap[e.code]
    if (control) {
      controls[control] = true
    }
  }
  
  const onKeyUp = (e) => {
    const control = keyMap[e.code]
    if (control) {
      controls[control] = false
    }
  }
  
  onMounted(() => {
    window.addEventListener('keydown', onKeyDown)
    window.addEventListener('keyup', onKeyUp)
  })
  
  onUnmounted(() => {
    window.removeEventListener('keydown', onKeyDown)
    window.removeEventListener('keyup', onKeyUp)
  })
  
  const setupControls = (isPlayer1) => {
    return isPlayer1 ? 
      reactive({
        left: false,
        right: false,
        up: false,
        attack1: false,
        attack2: false,
        special: false
      }) :
      reactive({
        left: false,
        right: false,
        up: false,
        attack1: false,
        attack2: false,
        special: false
      })
  }
  
  return { controls, setupControls }
}